﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Interfleet.SE.UICompiler.Core.ClosureCompiler
{
    public class CCResultBuilder : ResultBuilder
    {
        internal CCResultBuilder(Arguments arguments)
            : this(arguments, new FileProvider())
        {

        }

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="arguments"></param>
        /// <param name="fileInfoProvider"></param>
        public CCResultBuilder(Arguments arguments, IFileProvider fileInfoProvider)
            : base(arguments, fileInfoProvider)
        {
            
        }

        /// <summary>
        /// Sets fileinfo on the <see cref="CompileResult"/>
        /// </summary>
        /// <param name="result"></param>
        /// <param name="compileTime"></param>
        private void SetFileInfoOnResult(CompileResult result, DateTime compileTime)
        {
            var sb = new StringBuilder();
            var path = Arguments.CompiledFileName;
            if (!FileInfoProvider.FileExists(path))
            {
                result.Success = false;
                sb.AppendLine("No file was created");
                return;
            }
            else
            {
                var creationTime = FileInfoProvider.GetLastWriteTime(path);
                sb.AppendLine("Compiled file: " + path);
                var ts = DateTime.Now.Subtract(creationTime);
                if (creationTime < compileTime)
                {
                    sb.AppendLine("A new file was not created");
                    sb.AppendLine("The current file was created " + creationTime.ToString("yyyy-MM-dd HH:mm:ss"));
                    result.Success = false;
                }
                else
                {
                    sb.AppendLine("Creation time: " + creationTime.ToString("yyyy-MM-dd HH:mm:ss"));
                }
            }
            result.StatusMessage = string.Concat(result.StatusMessage, Environment.NewLine, sb.ToString());
        }

        public override CompileResult Build(string statusMessage, DateTime compilationStartedAt)
        {
            var result = new CompileResult(Arguments.Files, Arguments.CompiledFileName);
            if (string.IsNullOrEmpty(statusMessage))
            {
                result.Success = true;
            }
            else
            {
                result.Success = false;
            }
            SetFileInfoOnResult(result, compilationStartedAt);
            if (!string.IsNullOrEmpty(statusMessage))
            {
                result.StatusMessage = string.Concat(result.StatusMessage, Environment.NewLine, statusMessage);
            }
            return result;
        }
    }
}
